<?php
/**
 * 手动更新订单为已支付状态
 */
$verify_result = true;
//计算得出通知验证结果
if ($_SESSION['memberID']!=1 || $_SESSION['sid']!=1
    || empty($_POST['out_trade_no']) ) {
    $verify_result = false;
}
if (empty($_POST['trade_no'])) {
    exit('请核对支付宝交易号！');
}
include("/var/www/html/new/com.inc.php");
include("/var/www/html/new/d/class/OrderRecord.php");
//include("/var/www/html/new/d/alipay/ali_order/func.inc.php");

define('ACTION_MONEY_ADD',0);
define('ACTION_MONEY_CUT',1);
define('ERROR_LOG', '/var/www/html/new/d/logs/alipay_pc/err_log_'.date('ymd').'.txt');
define('OK_LOG', '/var/www/html/new/d/logs/alipay_pc/log_'.date('ymd').'.txt');


if($verify_result) {//验证成功
    $out_trade_no   = $_POST['out_trade_no'];// 商户订单号
    $trade_no       = $_POST['trade_no']; // 支付宝交易号
    $trade_status   = $_POST['trade_status'];// 交易状态

    if($_POST['trade_status'] == 'TRADE_FINISHED') {
        write_logs("1:$trade_no:$out_trade_no:$trade_status\n", OK_LOG);
    }
    else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
        //判断该笔订单是否在商户网站中已经做过处理
		$s = new SoapClient(null,array(
            "location" => "http://localhost/open/openService/pft_insideMX.php",
            "uri" => "www.16u.com?ac_16u={$GLOBALS['_ac']}|pw_16u={$GLOBALS['_pw']}|auth_16u=true")
        );

        $str=<<<SQL
update pft_alipay_rec set status=1,dtime=now(),`trade_no`='$trade_no'
WHERE out_trade_no='$out_trade_no' limit 1
SQL;
        $GLOBALS['le']->query($str);
        $ordern = $out_trade_no;

        $or=new OrderRecord($out_trade_no, $s);
        $orders=$or->info();

        total_fee($orders);

        $aid = (string)$orders['mainOrder']->UUaid;
        $mid = (string)$orders['mainOrder']->UUmid;
        fenRun($s,$out_trade_no,$total_fee,$orders,true);

        if ($_POST['send_sms']==1) {
            include '/var/www/html/new/d/class/OrderSmsManual.class.php';
            $smsManual  = new \PFT\SMS\OrderSmsManual($s);
            $ret = $smsManual->SendByOrderInfo($orders);
            if ($ret!=100) {
                write_logs("短信发送失败|订单号[$out_trade_no]|返回代码[$ret]", ERROR_LOG);
            } else {
                write_logs("短信发送成功|订单号[$out_trade_no]|返回代码[$ret]", OK_LOG);
            }
        }


        $ret = $s->Mod_Order_Status($out_trade_no,1,1);
        write_logs("手动-更新订单状态|订单号[$out_trade_no]|返回代码[$ret]", OK_LOG);
        //更新远端订单号
        $ret = $s->Remote_Ordernum_Update(serialize(array($out_trade_no=>'PC_ALIPAY_PFT_'.$_SERVER['REQUEST_TIME'])));
        write_logs("手动-更新远端订单号|订单号[$out_trade_no]|返回代码[]", OK_LOG);

        //发送微信通知
        if (!defined('DEFAULT_WECHAT_APPID')) {
            define('DEFAULT_WECHAT_APPID', 'wxd72be21f7455640d');//票付通公众号
            //TODO::包含全局文件
            include '/var/www/html/wx/wechat/iwx.php';
        }

        //STEP TWO->获取openid
        $sqlWx = "SELECT fromusername FROM uu_wx_member_pft WHERE fid=$mid AND tousername='".DEFAULT_WECHAT_APPID."' LIMIT 1";
        $stmt = \LaneWeChat\Core\Db::Connect()->prepare($sqlWx);
        $stmt->execute();
        $wx_open_id = $stmt->fetchColumn(0);
//            write_logs("sqlWx=$sqlWx" . $stmt->errorInfo());
        if ($wx_open_id) {
            $data        = array(
                'first'=> array('value'=>'订单提交成功','color'=>'#173177'),
                'tradeDateTime'=> array('value'=>(string)$orders['mainOrder']->UUordertime,'color'=>'#173177'),
                'orderType'=> array('value'=> '门票预定','color'=>'#ff9900'),
                'customerInfo'=> array('value'=> (string)$orders['mainOrder']->UUordername,'color'=>'#173177'),
                'orderItemName'=> array('value'=> (string)$orders['mainOrder']->UUltitle,'color'=>'#173177'),
                'orderItemData'=> array('value'=> (string)$orders['mainOrder']->UUttitle . (int)$orders['mainOrder']->UUtnum .'张','color'=>'#173177'),
                'remark'       => array('value'=> "订单号：{$out_trade_no}",'color'=>''),
            );
            \LaneWeChat\Core\TemplateMessage::sendTemplateMessage($data,
                $wx_open_id, '5QVNlRb5D9Fw3mFGIF5fhonoH42FPAbwllu5Au2013c',
                "http://wx.12301.cc/html/order_detail.html?fromt=f542e9fac6e76f4b3b66422d49e5585c&ordernum={$out_trade_no}",
                '#FF0000');
//                write_logs("TemplateMessage|RES=" .json_encode($msgRet));
        }
    }
    //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
    echo "处理成功，好棒！感谢您的使用";        //请不要修改或删除
    write_logs("2:$trade_no:$out_trade_no:$trade_status\n", OK_LOG);
}
else {
    //验证失败
    echo "fail";
    write_logs("3:$trade_no:$out_trade_no:$trade_status\n", ERR_LOG);
}

// 转分销分润
function fenRun($s,$ordern,$total_fee,$orders,$to_pft){
    
    $aid = (string)$orders['mainOrder']->UUaid;
    $mid = (string)$orders['mainOrder']->UUmid;
    $add = 0; $cut = 1;
	
    // 非自供产品获取结算价
    if($aid!=$mid){
        $total_money = 0;
        $pid = (string)$orders['mainOrder']->UUpid;// 产品 id
        $begintime = (string)$orders['mainOrder']->UUbegintime;// 游玩时间价格
        $account = (string)$orders['mainOrder']->UUfromt;// 游玩时间价格
        $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
        if($ret==105||$ret==1065){
            $total_money = $total_fee;
        }else{
            $obj = simplexml_load_string($ret);
            $total_money = (string)$obj->Rec->UUsprice * (int)$orders['mainOrder']->UUtnum;
        }
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $pid = (string)$child->UUpid;// 产品 id
                $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
                if($ret!=105 && $ret!=1065){
                    $obj = simplexml_load_string($ret);
                    $total_money += (string)$obj->Rec->UUsprice * (int)$child->UUtnum;
                }
            }
        }
    }
    
    if($to_pft){
        //票付通总账号加钱——2015年4月13日11:56:33林农说要添加，宝椿提供的代码
        $s->PFT_Member_Fund_Modify(1, 0, $total_fee, $add, 0,null,0, 0,$ordern);
        // 支付给了票付通，最下级供应商加钱
        $s->PFT_Member_Fund_Modify($aid, 0, $total_fee, $add, 0,null,0, 1,$ordern);
    }


    // 产品多级销售分润
    $str="select aids_money from uu_order_fx_details where orderid='$ordern' limit 1";
    $GLOBALS['le']->query($str);
    $lirun = $GLOBALS['le']->fetch_assoc();
    if ($lirun['aids_money']){

        // 子票没有记录分润，获取子票价格
        $childMenoy = array();
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $aids = explode(',',(string)$child->UUaids);
                krsort($aids);
                $aids_price = explode(',',(string)$child->UUaids_price);
                krsort($aids_price);
                foreach($aids as $k=>$et){
                    if($k==0) break;// 最后一个不用操作了
                    $childMenoy[$et]+= $aids_price[$k-1] * (string)$child->UUtnum;
                }
            }
        }
        // 主订单的 aids
        $main_aids = explode(',',(string)$orders['mainOrder']->UUaids);
        $aids_money = unserialize($lirun['aids_money']);
        $opID = 0;
        foreach($aids_money as $row){
            $fid=$row[0];
            $action = ($row[2]==0) ? $cut : $add;//0减少,1增加和接口相反
            $Mmoney=$row[3];
            if($action==0){ // 加钱
                $ks = array_search($fid,$main_aids);
                $ks = $ks+1;
                $Mmoney += isset($childMenoy[$main_aids[$ks]]) ? $childMenoy[$main_aids[$ks]]:0;
            }else{
                $Mmoney += isset($childMenoy[$fid]) ? $childMenoy[$fid]:0;
            }

            if($row[1]==0){//信用额度
                $dmode = 1;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,$row[4],0,2,$ordern);
            }else{//资金
                $dmode = 0;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,NULL,0,0,$ordern);
            }
        }
    }
    return $total_money;// 返回上级利润
}

// 获取订单总价格，以分为单位
function total_fee($orders){
    $total_fee = 0;
    $aid = (string)$orders['mainOrder']->UUaid;
	$mid = (string)$orders['mainOrder']->UUmid;
	
    $total_fee=((string)$orders['mainOrder']->UUtprice * (string)$orders['mainOrder']->UUtnum);
    $ordernum = (string)$orders['mainOrder']->UUordernum;
    $str=<<<SQL
insert pft_member_alipay set fid=$mid,orderid='$ordernum',
total_fee='$total_fee',money='$total_fee',ali_account='',rectime=now(),
dtype=0,daction=1
SQL;
    $GLOBALS['le']->query($str);
            
    // 加上非套票的子票价格
    if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
        foreach($orders['childOrder'] as $key=>$child){
            $tmp = (int)$child->UUtprice * (int)$child->UUtnum;
            $total_fee+=$tmp;
            $ordernum = (string)$child->UUordernum;
            $str=<<<SQL
INSERT pft_member_alipay set fid=$mid,orderid='$ordernum',
total_fee='$tmp',money='$tmp',ali_account='',rectime=now(),dtype=0,daction=1
SQL;
            $GLOBALS['le']->query($str);
        }
    }
    return $total_fee;
}


function write_logs($txt,$file='/var/www/html/alipay/new_log.txt'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}
?>